<template>
  <div class="content">
    <teacher-menu/>
    <main class="ml-64 flex-1 p-6 bg-gray-50 min-h-screen">

      <!-- 头部 -->
      <header class="flex justify-between items-center mb-6">
        <div class="flex items-center space-x-2">
          <svg class="w-7 h-7 text-blue-500" fill="currentColor" viewBox="0 0 24 24">
            <path
                d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v3h20v-3c0-3.3-6.7-5-10-5z"/>
          </svg>
          <h1 class="text-2xl font-semibold text-gray-800">学生简历管理中心</h1>
        </div>
      </header>

      <!-- 数据统计区域 -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white p-4  rounded-lg">
          <div class="text-gray-500 text-sm">简历总数</div>
          <div class="text-2xl font-bold text-blue-600">{{ totalResumes }}</div>
        </div>
        <div class="bg-white p-4  rounded-lg">
          <div class="text-gray-500 text-sm">已提交简历学生数</div>
          <div class="text-2xl font-bold text-green-600">{{ submittedCount }}</div>
        </div>
        <div class="bg-white p-4  rounded-lg">
          <div class="text-gray-500 text-sm">未提交简历学生数</div>
          <div class="text-2xl font-bold text-yellow-600">{{ unsubmittedCount }}</div>
        </div>
        <div class="bg-white p-4  rounded-lg">
          <div class="text-gray-500 text-sm">待评价简历数</div>
          <div class="text-2xl font-bold text-red-600">{{ pendingReviewCount }}</div>
        </div>
      </div>
      <el-tabs v-model="activeTab" type="card" @tab-click="handleClick">
        <!-- 管理标签页 -->
        <el-tab-pane label="简历管理" name="manage">
          <!-- 操作 -->
          <el-card class="search-card luodeng" shadow="never">
            <el-button icon="el-icon-edit" size="small" type="text" @click="editResume(currentRow)">编辑简历</el-button>
            <el-button icon="el-icon-plus" v-if="isTeacherCanAddResume" size="small" type="text" @click="addResume">
              新增简历
            </el-button>
            <el-button v-if="isTeacherCanSubmit" icon="el-icon-chat-dot-square" size="small" type="text"
                       @click="pjResume">评价
            </el-button>
            <el-button icon="el-icon-chat-dot-square" size="small" type="text"
                       @click="exportFileToPdf3">导出PDF
            </el-button>
          </el-card>
          <el-table
              :data="paginatedResumes"
              border
              class="w-full"
              highlight-current-row
              stripe
              @current-change="handleCurrentChange"
              @row-dblclick="previewResume"
          >
            <el-table-column label="简历代码" prop="JLDM" width="100"></el-table-column>
            <el-table-column label="学生姓名" prop="XSXM" width="150"></el-table-column>
            <el-table-column label="发布时间" prop="FBSJ" width="180">
              <template #default="{ row }">
                {{ row.FBSJ | dateFormat }}
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="FBSJ" width="180">
              <template #default="{ row }">
                {{ row.CJSJ | dateFormat }}
              </template>
            </el-table-column>

            <el-table-column label="上次修改时间" prop="FBSJ" width="180">
              <template #default="{ row }">
                {{ row.SCXGTIME | dateFormat }}
              </template>
            </el-table-column>
            <el-table-column label="阅读次数" prop="YDCS" width="150"></el-table-column>
            <el-table-column label="状态" prop="FBBZ" width="150">
              <template #default="{ row }">
                <el-tag :type="row.FBBZ === 1 ? 'success' : 'info'">
                  {{ row.FBBZ === 1 ? '已发布' : '草稿' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="提交状态" prop="TJZT" width="180">
              <template #default="{ row }">
                {{ getTjzt(row.TJZT) }}
              </template>
            </el-table-column>
            <el-table-column label="附件" width="150">
              <template #default="{ row }">
                <el-button
                    :disabled="!row.JLFJ"
                    icon="el-icon-download"
                    size="mini"
                    type="text"
                    @click="downloadAttachment(row)"
                >
                  下载附件
                </el-button>
              </template>
            </el-table-column>
            <!-- 附件上传在表格中完成 -->
            <el-table-column label="上传附件" width="200">
              <template #default="{ row }">
                <el-upload
                    :action="`/xsjlk/uploadJlfj`"
                    :auto-upload="true"
                    :data="{ jldm: row.JLDM }"
                    :file-list="row.uploadList"
                    :limit="1"
                    :on-success="res => handleRowUploadSuccess(row, res)"
                    class="upload-demo"
                    list-type="text"
                    name="file"
                >
                  <el-button size="mini" type="text">上传附件</el-button>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="270">
              <template #default="{ row }">
                <el-button size="mini" @click="editResume(row)">编辑</el-button>
                <el-button
                    :type="row.FBBZ === 1 ? 'danger' : 'primary'"
                    size="mini"
                    @click="togglePublish(row,row.FBBZ === 1? 0 : 1)"
                >
                  {{ row.FBBZ === 1 ? '取消发布' : '发布' }}
                </el-button>
                <el-button v-if="row.TJZT === 1" size="mini" @click="cxSubmit(row)">撤销提交</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="flex justify-end mt-4">
            <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[5,8, 10, 20, 50]"
                :total="total"
                background
                layout="prev, pager, next, sizes, total"
                @current-change="handlePageChange"
                @size-change="handleSizeChange"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="简历评价" name="jlpj">
          <div class="row">
            <div class="col-md-8">
              <el-card shadow="never">
                <el-table
                    :data="pjList"
                    border
                    class="w-full"
                    @row-dblclick="handlePjClick"
                    highlight-current-row
                    stripe>
                  <el-table-column label="简历代码" prop="JLDM" fixed="left" width="100"></el-table-column>
                  <el-table-column label="学生姓名" prop="XSXM" width="100"></el-table-column>
                  <el-table-column fixed="left" label="评价标志" prop="PJBZ" width="100">
                    <template #default="{ row }">
                      <el-tag :type="row.PJBZ === 1 ?'success' : 'danger'">
                        {{ row.PJBZ === 1 ? '已评价' : '未评价' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="评价人" prop="PJRXM" width="150"></el-table-column>
                  <el-table-column label="评分" prop="PF" width="150"></el-table-column>
                  <el-table-column label="评语" prop="PY" width="300"></el-table-column>
                  <el-table-column label="评价时间" prop="PJSJ" width="200">
                    <template #default="{ row }">
                      {{ row.PJSJ | dateFormat }}
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" width="100">
                    <template #default="{ row }">
                      <el-button size="mini"  @click="pj(row)">评价</el-button>
                      <el-button size="mini" @click="exportFileToPdf2(row)">导出</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>

            <div class="col-md-4">
              <el-card shadow="never">
                <div id="chat-container">
                  <form id="chat-form" onsubmit="return false;">
                    <label for="question"><strong>问题：</strong></label>
                    <textarea id="question" v-model="question" name="question" placeholder="在此输入您的问题…"
                              rows="4"></textarea>

                    <div style="display: flex; align-items: center; gap: 60px;">
                      <label>
                        <input v-model="isChecked" type="checkbox"/>
                        提交个人信息
                      </label>

                      <label>
                        <input v-model="isChecked2" type="checkbox"/>
                        HTML代码
                      </label>
                      <button id="askBtn" type="button" @click="clearChatHistory">清除记录</button>
                      <button id="askBtn" type="button" @click="askQuestion">提交问题</button>
                    </div>

                  </form>

                  <div id="response-container">
                    <label for="response"><strong>建议：</strong></label>
                    <!--                    <textarea id="response" v-model="answer" placeholder="智能回复会显示在这里…" readonly rows="20"></textarea>-->
                    <div v-show="!isChecked2" class="fake-textarea" v-html="formattedAnswer"></div>
                    <div v-show="isChecked2" class="fake-textarea" v-text="formattedAnswer"></div>
                    <button id="copyBtn" type="button">复制回复</button>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
        <!-- 编辑标签页 -->
        <el-tab-pane label="简历编辑" name="edit">
          <div class="row">
            <div class="col-md-8">
              <el-card shadow="never">
                <el-form ref="form" :model="form" :rules="rules" label-width="100px"
                         style="position: relative;right: 53px;">
                  <el-form-item label="选择学生" prop="">
                    <el-select v-model="form.STUID" clearable filterable placeholder="请选择学生">
                      <el-option v-for="(item, index ) in studentList" :key="index" :label="item.XSXM+'-'+item.XSXH"
                                 :value="item.ID"></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item>
                    <div ref="editor" class="editor-container"></div>
                    <el-input v-show="true" v-model="form.HTML"></el-input>
                  </el-form-item>
                  <div id="html-preview" style="position: absolute; left: -9999px; top: -9999px;"></div>
                  <el-form-item class="mt-6">
                    <el-button type="primary" @click="submitForm">保存</el-button>
                    <el-button @click="resetForm">重置</el-button>
                    <el-button @click="copyPersonalInfo">复制个人信息</el-button>
                    <el-button @click="exportFileToPdf(form.HTML,form.STUID)">导出文件</el-button>
                    <el-button @click="copyPersonalInfo">导入本地文件</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>

            <div class="col-md-4">
              <el-card shadow="never">
                <div id="chat-container">
                  <form id="chat-form" onsubmit="return false;">
                    <label for="question"><strong>问题：</strong></label>
                    <textarea id="question" v-model="question" name="question" placeholder="在此输入您的问题…"
                              rows="4"></textarea>
                    <div style="display: flex; align-items: center; gap: 60px;">
                      <label>
                        <input v-model="isChecked" type="checkbox"/>
                        提交个人信息
                      </label>

                      <label>
                        <input v-model="isChecked2" type="checkbox"/>
                        HTML代码
                      </label>
                      <button id="askBtn" type="button" @click="clearChatHistory">清除记录</button>
                      <button id="askBtn" type="button" @click="askQuestion">提交问题</button>
                    </div>

                  </form>

                  <div id="response-container">
                    <label for="response"><strong>建议：</strong></label>
                    <!--                    <textarea id="response" v-model="answer" placeholder="智能回复会显示在这里…" readonly rows="20"></textarea>-->
                    <div v-show="!isChecked2" class="fake-textarea" v-html="formattedAnswer"></div>
                    <div v-show="isChecked2" class="fake-textarea" v-text="formattedAnswer"></div>
                    <button id="copyBtn" type="button">复制回复</button>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
        <!--        <el-tab-pane label="DeepSeeK" name="deepseek">
                  <iframe src="https://chat.deepseek.com/a/chat/s/fcb93c69-69d8-4a10-9d95-51a51d1fc881" style="width: 100%; height:800px; border: none;"></iframe>
                </el-tab-pane>
                <el-tab-pane label="文心一言" name="文心一言">
                  <iframe src="https://yiyan.baidu.com/" style="width: 100%; height:800px; border: none;"></iframe>
                </el-tab-pane>-->
      </el-tabs>

      <!-- 简历预览对话框 -->
      <el-dialog :visible.sync="previewVisible" title="简历预览" width="50%">
        <div v-html="previewContent"></div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="previewVisible = false">关闭</el-button>
        </span>
      </el-dialog>

      <!-- 教师评价对话框 -->
      <el-dialog :visible.sync="pjVisible" title="教师评价" width="50%">
        <el-form ref="pjForm" :model="pjForm" :rules="pjRules" label-width="100px">
          <el-form-item label="教师">
            <el-select v-model="pjForm.jiaoshi" placeholder="请选择教师">
              <el-option v-for="(item, index ) in MyTeachersList" :key="index" :label="item.jsmc"
                         :value="item.dlzh"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitPj">提交</el-button>
            <el-button @click="pjVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>


      <!-- 教师评价对话框 -->
      <el-dialog :visible.sync="pjVisible2" title="教师评价" width="50%">
        <el-form ref="pjForm" :model="pjReviewForm" :rules="pjReviewFormRules" label-width="100px">
          <el-form-item prop="pf" label="教师">
            <el-input-number v-model="pjReviewForm.pf" placeholder="请输入评分"></el-input-number>
          </el-form-item>
          <el-form-item prop="py" label="评语">
            <el-input type="textarea" v-model="pjReviewForm.py" placeholder="请输入评语、建议"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitPjjlk">提交</el-button>
            <el-button @click="pjVisible2 = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 可见但不在屏幕上 -->
      <div
          id="html-preview2"
          style="position: absolute; top: -9999px; left: -9999px; width: 794px; background: white; z-index: -1;"
      ></div>
    </main>
  </div>
</template>

<script>
import E from 'wangeditor';
import dayjs from 'dayjs';
import axios from 'axios';
import {EventBus} from "@/event-bus";
import {ServerIP} from "@/SystemConfig"
import SockJS from "sockjs-client";
import {NOWIP} from "@/NOWIP";
import Stomp from "webstomp-client";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import TeacherMenu from "@/components/teacher/Teacher_menu.vue";

export default {
  name: 'TeacherXsjlView',
  components: {TeacherMenu},
  filters: {
    dateFormat(val) {
      return val ? dayjs(val).format('YYYY-MM-DD HH:mm') : '--';
    }
  },
  watch: {
    // 新增：监听HTML内容变化实现双向绑定
    'form.HTML'(newVal) {
      if (this.isEditorUpdating) return
      this.updateEditorContent(newVal)
    }
  },
  data() {
    return {
      pjReviewFormRules: {
        pf: [
          {required: true, message: '请输入评分', trigger: 'blur'}
        ],
        py: [
          {required: true, message: '请输入评语', trigger: 'blur'}
        ]
      },
      currentPjjlk: {},
      pjVisible2: false,
      pjReviewForm: {
        pf: 0,
        py: '',
      },
      isTeacherCanAddResume: false, // 教师是否可以为学生新增简历
      studentList: [],
      totalResumes: 0,
      submittedCount: 0,
      unsubmittedCount: 0,
      pendingReviewCount: 0,

      pjList: [],//简历评价列表
      MyTeachersList: [],
      pjVisible: false,
      pjForm: {
        jiaoshi: '',
      },
      pjRules: {
        jiaoshi: [{required: true, message: '请输选择教师', trigger: 'blur'}]
      },
      isEditorUpdating: false, // 新增：防止循环更新标志
      isChecked2: false,
      isChecked: false,
      UserInfo: {
        id: '',
        name: '',
        role: '',
        username: '',
      },
      // 用来保存 STOMP 客户端实例
      stompClient: null,
      question: "",
      answer: "",


      activeTab: 'manage',
      // 模拟后端数据，初始化几条简历记录
      resumes: [],
      form: {
        STUID: '',
        JLDM: '',
        HTML: '',
        TEXT: '',
      },
      rules: {
        JLMC: [
          {required: true, message: '请输入简历名称', trigger: 'blur'}
        ]
      },
      student: {},
      currentRow: null,
      editor: null,
      previewVisible: false,
      previewContent: '',

      currentPage: 1,
      pageSize: 8,
      total: 0,

      isTeacherCanSubmit: false, // 教师是否可以提交学生的简历
    };
  },
  mounted() {
    this.getLoginUserInfo();// 获取登录用户信息
    this.initEditor();
    this.connectWebSocket();
    this.$socket.subscribe(this.handleWebSocketMessage)
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy();
      this.editor = null;
    }
    this.$socket.unsubscribe(this.handleWebSocketMessage)
  },
  methods: {
    exportFileToPdf2(row) {
      // 获取简历数据
      axios.get("/xsjlk/getXsjlDataAuto?YHM=" + this.UserInfo.username + "&JLDM=" + row.JLDM + "&YHSFDM=2")
          .then(response => {
            // 获取隐藏容器
            const previewContainer = document.getElementById("html-preview2");
            if (!previewContainer) {
              console.error("预览容器不存在");
              return;
            }

            const htmlContent = response.data.data[0].HTML;
            if (!htmlContent) {
              this.$message.error("简历内容为空");
              return;
            }

            // 设置 HTML 内容
            previewContainer.innerHTML = htmlContent;



            // 等 DOM 渲染完成再截图
            this.$nextTick(() => {
              html2canvas(previewContainer, {
                scale: 2,
                useCORS: true,
                allowTaint: true
              }).then((canvas) => {
                const imgData = canvas.toDataURL("image/png");

                const pdf = new jsPDF("p", "mm", "a4");
                const pageWidth = pdf.internal.pageSize.getWidth();
                const pageHeight = pdf.internal.pageSize.getHeight();

                const imgWidth = pageWidth;
                const imgHeight = (canvas.height * imgWidth) / canvas.width;

                let position = 0;
                let remainingHeight = imgHeight;

                while (remainingHeight > 0) {
                  pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
                  remainingHeight -= pageHeight;
                  if (remainingHeight > 0) {
                    pdf.addPage();
                    position = 0;
                  }
                }

                pdf.save(row.XSXM + "-简历.pdf");
              }).catch(error => {
                console.error("生成 PDF 失败：", error);
                this.$message.error("生成 PDF 失败：" + error.message);
              });
            });
          })
          .catch(error => {
            console.error("获取简历数据失败", error);
            this.$message.error("获取简历数据失败:" + error.message);
          });
    },
    exportFileToPdf3(){
      if (this.currentRow === null) {
        this.$message.warning("请选择简历！");
        return;
      }
      // 获取隐藏容器
      const previewContainer = document.getElementById("html-preview2");
      if (!previewContainer) {
        console.error("预览容器不存在");
        return;
      }

      const htmlContent = this.currentRow.HTML;
      if (!htmlContent) {
        this.$message.error("简历内容为空");
        return;
      }

      // 设置 HTML 内容
      previewContainer.innerHTML = htmlContent;

      // 等 DOM 渲染完成再截图
      this.$nextTick(() => {
            html2canvas(previewContainer, {
              scale: 2,
              useCORS: true,
              allowTaint: true
            }).then((canvas) => {
              const imgData = canvas.toDataURL("image/png");

              const pdf = new jsPDF("p", "mm", "a4");
              const pageWidth = pdf.internal.pageSize.getWidth();
              const pageHeight = pdf.internal.pageSize.getHeight();

              const imgWidth = pageWidth;
              const imgHeight = (canvas.height * imgWidth) / canvas.width;

              let position = 0;
              let remainingHeight = imgHeight;

              while (remainingHeight > 0) {
                pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
                remainingHeight -= pageHeight;
                if (remainingHeight > 0) {
                  pdf.addPage();
                  position = 0;
                }
              }

              pdf.save(this.currentRow.XSXM + "-简历.pdf");
            });
      });
    },

    // 双击查看简历
    handlePjClick(row, column, event) {
      console.log(row);
      // 获取简历数据
      axios.get("/xsjlk/getXsjlDataAuto?YHM=" + this.UserInfo.username + "&JLDM=" + row.JLDM + "&YHSFDM=2").then(response => {
        this.previewVisible = true;
        this.previewContent = response.data.data[0].HTML;
      }).catch(error => {
        this.$message.error("获取简历数据失败:" + error.message);
      });
    },
    submitPjjlk() {
      console.log(this.currentPjjlk);
      console.log(this.pjReviewForm);
      let PjData = new FormData();
      PjData.append("pf", this.pjReviewForm.pf);
      PjData.append("py", this.pjReviewForm.py);
      PjData.append("id", this.currentPjjlk.ID);
      PjData.append("pjbz", 1);
      axios.post('/xsjlk/updateJpgj', PjData).then(response => {
        if (response.data.result) {
          this.$message.success("评价成功");
          this.pjVisible2 = false;
          this.getXsjlData(); // 刷新简历
        } else {
          this.$message.error("评价失败: " + response.data.msg);
        }
      }).catch(error => {
        this.$message.error("评价失败: " + error.message);
      });
    },
    pj(row) {
      if (row.PJBZ === 1) {
        this.$message.warning("该简历已评价");
        return;
      }

      this.currentPjjlk = row;
      this.pjVisible2 = true;
    },
    async getStudetntList() {
      const response = await axios.get(`/student/getStudentDataNewInterface?YHM=${this.UserInfo.username}&YHSFDM=2&QYDM=1`);
      this.studentList = response.data.data;
    },
    handleClick(tab, event) {
      if (tab.index === "2") {
        if (this.studentList.length === 0) {
          this.getStudetntList();
        }
      }
    },
    // 撤销提交
    cxSubmit(row) {
      $.confirm({
        title: '确认撤销？',
        content: '你确定要撤销该学生的简历提交吗？',
        type: 'orange',
        buttons: {
          确认: {
            btnClass: 'btn-red',
            action: () => {
              axios.get("/xsjlk/csSubmit?JLDM=" + row.JLDM)
                  .then(response => {
                    if (response.data.result) {
                      this.$message.success("撤销提交成功");
                      this.getXsjlData(); // 刷新简历
                    } else {
                      this.$message.error("撤销提交失败: " + response.data.msg);
                    }
                  })
                  .catch(error => {
                    this.$message.error("撤销提交失败: " + error.message);
                  });
            }
          },
          取消: function () {
            // 用户点击取消，不做处理
          }
        }
      });
    },
    getTjzt(tjzt) {
      if (tjzt === 0) {
        return "未提交";
      } else if (tjzt === 1) {
        return "已提交待评价";
      } else if (tjzt === 2) {
        return "已提交已评价";
      }
    },
    getParams() {
      // 教师是否可以提交学生的简历/教师是否可以为学生新增简历
      axios.post('/config/getSemsConfigByIds',
          [33, 34],
          {headers: {'Content-Type': 'application/json'}}
      ).then(response => {
        this.isTeacherCanSubmit = response.data.find(item => item.id === 33).value === "是";
        this.isTeacherCanAddResume = response.data.find(item => item.id === 34).value === "是";
      }).catch(error => {
        this.$message.error('获取配置信息失败，请联系管理员');
      });
    },
    askQuestion() {
      console.log(this.question);
      // 提问者: this.UserInfo.username
      // 提问者姓名: this.UserInfo.name
      // 问题: this.question
      if (this.question.length === 0) {
        this.$message.warning("请输入问题！");
        return;
      }
      let newQuestion = this.question;
      console.log(this.isChecked)
      if (this.isChecked) {
        /* ` 注：姓名 ${this.student.XSXM}，性别 ${this.student.XSXB}，出生日期 ${this.student.BIRTH}，年龄 ${this.student.NL} 岁，` +
            `学号 ${this.student.YHM}，民族 ${this.student.MZ}，政治面貌 ${this.student.ZZMM}，入学年份 ${this.student.RXNF}，毕业年份 ${this.student.BYNF}，` +
            `所在学校 ${this.student.SZXX}，学历 ${this.student.XLMC}，学位 ${this.student.XW}，专业 ${this.student.ZYMC}，` +
            `班级 ${this.student.BJMC}，年级 ${this.student.SSNJ}，学制 ${this.student.XZ}，` +
            `当前状态 ${this.student.JYZT}，身份证号 ${this.student.SFZH}，联系电话 ${this.student.LXDH}，邮箱 ${this.student.YXDZ}，` +
            `所在地 ${this.student.SFCS}`;*/
      }

      // 发送给后台处理
      const newMsg = {
        twzyhm: this.UserInfo.username,//提问者用户名
        twzsfdm: 2,// 提问者身份代码
        twzyzxm: this.UserInfo.name,// 提问者姓名
        question: newQuestion,// 消息内容
        sendtime: new Date().getTime()
      };

      try {
        this.stompClient.send("/app/chat2", JSON.stringify(newMsg));
      } catch (error) {
        this.handleError('消息发送失败', error);
      }
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1; // 重置到首页
    },
    getpjList() {
      axios.get("/xsjlk/getJpgjList", {params: {YHM: this.UserInfo.username, JLDM: -1, YHSFDM: 2}}).then(response => {
        this.pjList = response.data.data;
      }).catch(error => {
        this.$message.error("获取评价列表失败:" + error.message);
      });
    },
    submitPj() {
      this.$refs.pjForm.validate(valid => {
        if (!valid) return;
        let PjData = new FormData();
        PjData.append("pjr", this.pjForm.jiaoshi);
        PjData.append("jldm", this.currentRow.JLDM);
        PjData.append("pjrsfdm", 2);

        // 提交表单数据（替换为你实际的后端接口地址）
        axios.post('/xsjlk/addJpgj', PjData)
            .then(response => {
              this.$message.success('提交成功');
              this.pjVisible = false;        // 关闭对话框
              this.$refs.pjForm.resetFields(); // 重置表单
              // 刷新简历
              this.getXsjlData();
            })
            .catch(error => {
              this.$message.error('提交失败，请稍后再试');
            });
      });
    },
    // 导出为PDF
    exportFileToPdf(HTML, name) {
      // 获取隐藏容器
      const previewContainer = document.getElementById("html-preview");
      if (!previewContainer) {
        console.error("预览容器不存在");
        return;
      }

      // 设置 HTML 内容
      previewContainer.innerHTML = HTML;

      html2canvas(previewContainer, {
        scale: 2,
        useCORS: true,
        allowTaint: true,
      }).then((canvas) => {
        const imgData = canvas.toDataURL("image/png");

        const pdf = new jsPDF("p", "mm", "a4");
        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();

        const imgWidth = pageWidth;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        let position = 0;
        let remainingHeight = imgHeight;

        while (remainingHeight > 0) {
          pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
          remainingHeight -= pageHeight;
          if (remainingHeight > 0) {
            pdf.addPage();
            position = 0;
          }
        }
        pdf.save(name + "-简历.pdf");
      });
    },
    copyPersonalInfo() {
      const safe = (val) => val !== undefined && val !== null ? val : "未定义";

      const text = `注：姓名 ${safe(this.student.XSXM)}，性别 ${safe(this.student.XSXB)}，出生日期 ${safe(this.student.BIRTH)}，年龄 ${safe(this.student.NL)} 岁，` +
          `学号 ${safe(this.student.YHM)}，民族 ${safe(this.student.MZ)}，政治面貌 ${safe(this.student.ZZMM)}，入学年份 ${safe(this.student.RXNF)}，毕业年份 ${safe(this.student.BYNF)}，` +
          `所在学校 ${safe(this.student.SZXX)}，学历 ${safe(this.student.XLMC)}，学位 ${safe(this.student.XW)}，专业 ${safe(this.student.ZYMC)}，` +
          `班级 ${safe(this.student.BJMC)}，年级 ${safe(this.student.SSNJ)}，学制 ${safe(this.student.XZ)}，` +
          `当前状态 ${safe(this.student.JYZT)}，身份证号 ${safe(this.student.SFZH)}，联系电话 ${safe(this.student.LXDH)}，邮箱 ${safe(this.student.YXDZ)}，` +
          `所在地 ${safe(this.student.SFCS)}，个人照片路径：${safe(this.student.XSZP)}。`;

      // 创建隐藏 textarea 元素
      const textarea = document.createElement('textarea');
      textarea.value = text;
      textarea.setAttribute('readonly', '');
      textarea.style.position = 'absolute';
      textarea.style.left = '-9999px';
      document.body.appendChild(textarea);

      // 选中内容并执行复制命令
      textarea.select();
      try {
        const success = document.execCommand('copy');
        if (success) {
          this.$message.success("复制成功");
        } else {
          this.$message.error("复制失败");
        }
      } catch (err) {
        this.$message.error("复制异常");
        console.error("复制出错:", err);
      }

      // 移除 textarea
      document.body.removeChild(textarea);
    },
    clearChatHistory() {
      let clearForm = new FormData();
      clearForm.append("twz", this.UserInfo.username);
      clearForm.append("twzsfdm", 4);

      axios.post("/aidhjlk/clear", clearForm).then(response => {
        if (response.data.result) {
          this.$message.success("清除记录成功");
        } else {
          this.$message.error("清除记录失败:" + response.data.msg);
        }
      }).catch(error => {
        this.$message.error("清除记录失败:" + error.message);
      });

    },
    // 更新编辑器内容（新增方法）
    updateEditorContent(html) {
      if (!this.editor || this.editor.txt.html() === html) return
      // 保存选区
      const selection = window.getSelection()
      const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : null
      // 更新内容
      this.editor.txt.html(html)

      // 恢复选区
      if (range) {
        selection.removeAllRanges()
        selection.addRange(range)
      }
    },
    // 连接WebSocket
    connectWebSocket() {
      const socket = new SockJS(`http://${NOWIP}:83/chat`);
      this.stompClient = Stomp.over(socket);

      this.stompClient.connect({}, () => {
        this.stompClient.subscribe('/topic/messages', message => {
          const msg = JSON.parse(message.body);
          /*  answer:"一万字，是一个相对来说较为庞大的篇幅。在写作过程中，需要有足"
            question:
                "10000字！！"
            sendtime
                :
                "2025-05-07T05:02:25.530+00:00"
            twzsfdm
                :
                "4"
            twzyhm
                :
                "20213260021"
            twzyzxm
                :
                "陈洁梅"*/
          //一点点把回答放到answer中
          this.answer = msg.answer;
        });
      });
    },
    pjResume() {
      if (this.currentRow === null) {
        this.$message.warning("请选择简历！");
        return;
      }
      if (this.currentRow.TJZT === 1) {
        this.$message.warning("该简历已提交评价！无需重复提交！");
        return;
      }

      //获取学生的老师
      axios.get("/teacher/getTeacherByStuid?stuid=" + this.currentRow.XSID).then(response => {
        this.MyTeachersList = response.data.data;
      }).catch(error => {
        this.$message.error("获取教师列表失败:" + error.message);
      });

      this.pjVisible = true;
    },
    handleWebSocketMessage(msg) {
      console.log('Received message in component:', msg)
      // 处理你的消息
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    downloadAttachment(row) {
      if (!row.JLFJ) {
        this.$message.warning('暂无附件可下载');
        return;
      }
      // 使用浏览器方式打开下载链接（确保是完整URL）
      window.open(ServerIP + row.JLFJ, '_blank');
    },
    handleRowUploadSuccess(row, res) {
      // 比如后端返回 { data: { attachmentUrl: '…' } }
      row.uploadList = [{
        name: res.data.filename || '附件.pdf',
        url: res.data.attachmentUrl,
        status: 'finished'
      }];
    },

    async getLoginUserInfo() {
      try {
        this.loading = true;
        const response = await axios.get('/user/checkSession');
        if (!response.data.result) {
          this.handleAuthFailure(response.data.msg);
        } else {
          this.UserInfo = {
            name: response.data.name,
            role: response.data.role,
            username: response.data.username
          };
          this.getXsjlData();
          this.getpjList();
          this.getParams();
        }
      } catch (error) {
        console.error('获取用户信息失败，网络错误！', error);
        this.handleAuthFailure();
      }
    },
    getXsjlData() {
      axios.get("/xsjlk/getXsjlDataAuto?YHM=" + this.UserInfo.username + "&JLDM=-1&YHSFDM=2").then(response => {
        this.resumes = response.data.data;
        this.total = this.resumes.length; // 本地分页时使用
        // 统计
        this.totalResumes = this.resumes.length,
            this.submittedCount = this.resumes.filter(item => item.TJZT === 1 || item.TJZT === 2).length;
        this.unsubmittedCount = this.resumes.filter(item => item.TJZT === 0).length;
        this.pendingReviewCount = this.resumes.filter(item => item.TJZT === 1).length;


      }).catch(error => {
        $.confirm({
          title: '提示',
          content: '获取简历数据失败：' + error.message,
          type: 'red', // warning 样式
          buttons: {
            重试: {
              btnClass: 'btn-orange',
              action: () => {
                this.getXsjlData();
              }
            },
            取消: () => {
              this.$message('已取消操作');
            }
          }
        });
      });
    },
    initEditor() {
      this.editor = new E(this.$refs.editor);
      this.editor.config.height = 600
      // 基础配置
      this.editor.config.zIndex = 100
      this.editor.config.onchange = (html) => {
        this.form.HTML = html;
        this.form.TEXT = this.editor.txt.text(); // 纯文本内容
      };
      this.editor.config.lineHeights = ['1', '1.15', '1.6', '2', '2.5', '3']
      // 图片上传配置
      this.editor.config.uploadImgServer = '/xsjlk/uploadImg'
      this.editor.config.uploadFileName = 'file'
      this.editor.config.uploadImgMaxSize = 100 * 1024 * 1024 // 100MB
      this.editor.config.uploadImgHooks = {
        customInsert: (insertImg, result) => {
          if (result.result) {
            insertImg(result.data)
          }
        }
      }
      // 视频上传配置
      this.editor.config.uploadVideoServer = '/dw/uploadVideo'
      this.editor.config.uploadVideoName = 'videoFile'
      this.editor.config.uploadVideoMaxSize = 300 * 1024 * 1024 //  300MB
      this.editor.config.uploadVideoHooks = {
        before: (video) => {
          this.$message.info('视频上传中...')
          return true
        },
        success: (file, res) => {
          this.$message.success('视频上传成功')
        },
        fail: (file, err, res) => {
          this.$message.error(`视频上传失败: ${err.message || err}`)
        },
        error: (file, err, res) => {
          this.$message.error(`上传错误: ${err.message || err}`)
        },
        customInsert: (insertVideo, res) => {
          if (res.code === 200) {
            insertVideo(res.data)
          } else {
            this.$message.error(res.message || '视频插入失败')
          }
        }
      }
      // 配置行高
      this.editor.config.lineHeights = ['1', '1.15', '1.6', '2', '2.5', '3']
      // 菜单栏配置
      this.editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'todo',
        'justify',
        'quote',
        'emoticon',
        'image',
        'video',
        'table',
        'code',
        'splitLine',
        'undo',
        'redo',
      ]
      this.editor.create();
    },
    // 模拟编辑操作：将行数据加载到编辑表单中
    editResume(row) {
      if (row === null) {
        $.confirm({
          title: '温馨提示',
          content: '请先选择简历！',
          type: 'orange',
          animation: 'shake',              // 抖动出现
          closeAnimation: 'scale',         // 缩放消失（可选）
          animateFromElement: false,       // 居中弹出，不依赖点击元素
          buttons: {
            confirm: {
              text: '确定',
              btnClass: 'btn-orange',
              action: () => {
                console.log('用户确认继续');
              }
            }
          }
        })
        return;
      }
      if (this.studentList.length === 0) {
        this.getStudetntList();
      }
      console.log(row);

      this.form.STUID = row.XSID;
      this.form.JLDM = row.JLDM;
      this.form.HTML = row.HTML;
      this.form.TEXT = row.JLWB;

      this.editor.txt.html(row.HTML);
      this.activeTab = 'edit';
    },
    // 保存编辑内容（模拟后端数据保存）
    submitForm() {
      console.log(this.form);
      this.$refs.form.validate(valid => {
        if (valid) {
          let XSJLDATA = new FormData();
          XSJLDATA.append("xsid", this.form.STUID);
          XSJLDATA.append("jlwb", this.form.TEXT);
          XSJLDATA.append("html", this.form.HTML);

          // 若JLDM存在，说明是编辑，否则为新增
          if (this.form.JLDM) {
            // 编辑简历
            XSJLDATA.append("jldm", this.form.JLDM);
            axios.post("/xsjlk/updateResume", XSJLDATA).then(response => {
              if (response.data.result) {
                this.$message.success('简历保存成功！');
                // 插入消息，通知学生，老师已经修改了简历


                // 更新数据
                this.getXsjlData();
              } else {
                $.confirm({
                  title: '严重错误',
                  content: '简历保存失败:' + response.data.msg,
                  type: 'red',
                  buttons: {
                    retry: {
                      text: '重试',
                      btnClass: 'btn-red',
                      action: () => {
                        this.submitForm();
                      }
                    },
                    cancel: {
                      text: '取消',
                      action: () => {
                        // 用户取消
                      }
                    }
                  }
                });
              }
            }).catch(error => {
              $.confirm({
                title: '严重错误',
                content: '简历保存失败:' + error.message,
                type: 'red',
                buttons: {
                  retry: {
                    text: '重试',
                    btnClass: 'btn-red',
                    action: () => {
                      this.submitForm();
                    }
                  },
                  cancel: {
                    text: '取消',
                    action: () => {
                      // 用户取消
                    }
                  }
                }
              });
            });
          } else {
            // 新增简历
            XSJLDATA.append("fbbz", 0);
            axios.post("/xsjlk/addResume", XSJLDATA).then(response => {
              if (response.data.result) {
                this.resumes.push({...this.form, JLDM: response.data.data.JLDM, uploadList: []});
                this.$message.success('简历保存成功！');
                this.getXsjlData();
              } else {
                $.confirm({
                  title: '严重错误',
                  content: '简历保存失败:' + response.data.msg,
                  type: 'red',
                  buttons: {
                    retry: {
                      text: '重试',
                      btnClass: 'btn-red',
                      action: () => {
                        this.submitForm();
                      }
                    },
                    cancel: {
                      text: '取消',
                      action: () => {
                        // 用户取消
                      }
                    }
                  }
                });
              }
            }).catch(error => {
              $.confirm({
                title: '严重错误',
                content: '简历保存失败:' + error.message,
                type: 'red',
                buttons: {
                  retry: {
                    text: '重试',
                    btnClass: 'btn-red',
                    action: () => {
                      this.submitForm();
                    }
                  },
                  cancel: {
                    text: '取消',
                    action: () => {
                      // 用户取消
                    }
                  }
                }
              });
            });
            // 新增一条记录
            this.resumes.push({...this.form, uploadList: []});
            this.$message.success('新增成功');
          }
          this.activeTab = 'manage';
        }
      });
    },
    addResume() {
      this.activeTab = 'edit';
      this.resetForm();
      if (this.studentList.length === 0) {
        this.getStudetntList();
      }

    },
    resetForm() {
      this.$refs.form.resetFields();
      this.editor.txt.clear();
    },
    handleAuthFailure() {
      EventBus.$emit('show-auth-popup');
      setTimeout(() => {
        this.$router.push({name: 'StudentLoginView'});
      }, 1000);
    },
    togglePublish(row, fbbz) {
      if (fbbz === 1 && row.TJZT === 0) {
        this.$confirm('此简历还未评价，确定发布该简历吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let NewData = new FormData();
          NewData.append("jldm", row.JLDM);
          NewData.append("fbbz", fbbz);
          axios.post("/xsjlk/updateResume", NewData).then(response => {
            if (response.data.result) {
              this.$message.success((fbbz === 1 ? '发布' : '取消发布') + '成功！');
              row.FBBZ = fbbz;
            } else {
              $.confirm({
                title: '严重错误',
                content: (fbbz === 1 ? '发布' : '取消发布') + '失败:' + response.data.msg,
                type: 'red',
                buttons: {
                  retry: {
                    text: '重试',
                    btnClass: 'btn-red',
                    action: () => {
                      this.togglePublish(row, 1);
                    }
                  },
                  cancel: {
                    text: '取消',
                    action: () => {
                      // 用户取消
                    }
                  }
                }
              });
            }
          }).catch(error => {
            $.confirm({
              title: '严重错误',
              content: '失败:' + error.message,
              type: 'red',
              buttons: {
                retry: {
                  text: '重试',
                  btnClass: 'btn-red',
                  action: () => {
                    this.togglePublish(row, fbbz);
                  }
                },
                cancel: {
                  text: '取消',
                  action: () => {
                    // 用户取消
                  }
                }
              }
            });
          });
        }).catch(() => {
          return;
        });
      }
    },
    // 双击表格行时预览简历内容
    previewResume(row) {
      this.previewContent = row.HTML;
      this.previewVisible = true;
    }
  },
  computed: {
    studentId() {
      return this.$store.state.user.id;
    },
    formattedAnswer() {
      // 替换所有 `\n` 成 <br>（注意这里是匹配字符串中的字面量 \n）
      return this.answer.replace(/\\n/g, '<br>');
    },
    paginatedResumes() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.resumes.slice(start, end);
    }
  }
};
</script>

<style scoped>
#chat-container {
  /*max-width: 600px;*/
  margin: 2px auto;
  padding: 15px;
  /* border: 1px solid #ccc;
   border-radius: 8px;*/
  font-family: sans-serif;
}

textarea {
  width: 100%;
  box-sizing: border-box;
  padding: 8px;
  margin: 5px 0 10px;
  border: 1px solid #aaa;
  border-radius: 4px;
  resize: vertical;
  font-size: 14px;
}


.editor-container {
  /*border: 1px solid #dcdfe6;*/
  border-radius: 4px;
  padding: 10px;
  /* 设置编辑器高度 */
  min-height: 300px;
}

.w-e-toolbar {
  /* border-bottom: 1px solid #dcdfe6 !important;*/
}

.w-e-text-container {
  height: 300px !important;
}

.form-container {
  padding: 2px;
  background: #ffffff;
  border-radius: 0px;
  /*  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);*/
}

.luodeng button {
  margin-right: 30px !important;
}

.fake-textarea {
  border: 1px solid #ccc;
  padding: 8px;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5; /* 每行高度约 21px */
  height: calc(1.5em * 26); /* 20 行 */
  overflow-y: auto;
  background-color: #f9f9f9;
  white-space: normal; /* 必须是 normal，否则 <br> 无效 */
  word-break: break-word;
}


</style>
